package dk.dtu.student.assignmentfour;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;

public class Afinn {
	
	Map<String, Integer> afinn = new HashMap<String, Integer>();
	FileReader fr;
	BufferedReader br;
	File file;
	
	public Afinn(Context context) throws IOException {
		InputStream is = context.getAssets().open("AFINN-111.txt");
		br = new BufferedReader(new InputStreamReader(is));
		
		String line = "";
		while ((line = br.readLine()) != null) {
				String[] values = line.split("\t");
				String word = values[0].toLowerCase();
				Integer value = Integer.valueOf(values[1]);
				afinn.put(word, value);
		}
	}
	
	public double sentiment(String text) throws NumberFormatException, IOException {
		
		String[] words = text.toLowerCase().split(" ");
		
		double sum = 0;
		int foundWords = 0;
		for (String word : words) {
			if (afinn.containsKey(word)) {
				sum += afinn.get(word);
				foundWords++;
			}
		}
		
		if (foundWords == 0) {
			return 0;
		} else {
			//return sum/Math.sqrt(foundWords);
			return sum/foundWords;
		}
	}

}
